import items from "./routes.ts";
import emitter from "./emitter.ts";
import { checkPermissions } from "./permission.ts";
import { createRouter, createWebHashHistory } from 'vue-router';
import useUserStore from "../stores/system/user.ts";

const loadedPageSet:{[key: string]: boolean} = {}

//获取路由集合
const getRoutes = function(node: any[]){
    let res = [];
    for (let i = 0; i < node.length; i++) {
        if(node[i]?.type == "header")
            continue;
        res.push(node[i]);
    }
    return res;
};

//定义路由列表
const routes = getRoutes(items);

//创建路由实例
const router = createRouter({
    //history: createWebHistory(),
    history: createWebHashHistory(),
    routes,
});

//路由导航守卫(跳转前)
//@ts-ignore
router.beforeEach((to, from, next) => {
    //获取用户设置
    const userStore: any = useUserStore();
    //执行登录判断
    if(to?.meta["login"] !== false && (userStore.id == '' || userStore.token == '')){
        next("/login");
        return;
    }
    //执行权限判断
    if(to?.meta["permissions"] && !checkPermissions(<any>to?.meta["permissions"])){
        console.error("没有访问权限: " + to.path);
        return;
    }
    //是否曾经加载(未加载则显示加载)
    if(!loadedPageSet[to.path]){
        emitter.emit('loading', true)
    }
    //执行默认处理
    next();
});

//路由导航守卫(跳转后)
//@ts-ignore
router.afterEach((to) => {
    //是否曾经加载(未加载则关闭显示加载,并记录到曾经加载列表)
    if(!loadedPageSet[to.path]){
        loadedPageSet[to.path] = true;
        emitter.emit('loading', false)
    }
});

//返回路由对象
export default router;